/**
 * 微信授权控制器
 */
angular
.module('myApp')
.controller('wechatController', function($scope, $window, $location, $http, $routeParams, tokenManager, URL) {

  if (angular.isUndefined($routeParams.code)) {

    $.showLoading('正在跳转...');

    $http.get(URL+'/oauth2/authorizeAfterBind.php')
    .success(function(response) {
      if (response.code !== 200) {
        $scope.errorMessage = response.data;
      } else {
        $window.location.href = response.data;
      }
    })
    .error(function(response) {
      $scope.errorMessage = response.data;
    })
    .finally(function() {
      $.hideLoading();
    });

    return false;
  }

  $.showLoading('正在跳转...');

  var token = tokenManager.getToken();
  var query = {
    access_token: token.access_token,
    authorization_code: $routeParams.code
  };

  $http.get(URL+'/oauth2/authorizeAfterBind.php', {params: query})
  .success(function(response) {
    if (response.code !== 200) {
      $scope.errorMessage = response.data;
    } else {
      $location.path('/');
    }
  })
  .error(function(response) {
    $scope.errorMessage = response.data;
  })
  .finally(function() {
    $.hideLoading();
  });
});
